<template>
  <div class="sell-goods">
    <div class="common-space" style="height: 10px"></div>
    <CellGroup>
      <Cell
        class="sell-goods-cell"
        title="商品类型"
        :value="goodsInfo.goodsTypeName"
      />
      <Cell class="sell-goods-cell" title="卡种">
        <div class="sell-goods-cell-value">
          <div class="sell-goods-cell-value-img">
            <img :src="goodsInfo.goodsIcon" alt="" />
          </div>
          {{ goodsInfo.goodsName }}
        </div>
      </Cell>
      <Cell class="sell-goods-cell" title="规格" :value="goodsInfo.skuName" />
      <Cell
        class="sell-goods-cell"
        title="最短有效期"
        is-link
        :value="formData.pastTime"
        @click="showCalendar"
        v-if="goodsInfo.cardType !== 2"
      />
      <Cell class="sell-goods-cell" title="卡券售价" value="2020-10-10">
        <div class="sell-goods-cell-value">
          <div class="sell-goods-cell-value-price">
            ¥ {{ goodsInfo.realPrice }}
          </div>
          <div class="placeholder-right"></div>
        </div>
      </Cell>
      <Cell class="sell-goods-cell" v-if="goodsInfo.cardType === 1">
        <template #title>
          <div>
            上传兑换码
            <span class="sell-goods-cell-cansell">
              当前可寄售数量{{ acquireNumber }}</span
            >
          </div>
        </template>
        <template #label>
          <div class="sell-goods-upload">
            <div class="sell-goods-upload-tips">
              每批次最大输入100个，券码之间的以换行作为区分
            </div>
            <div class="sell-goods-upload-textarea">
              <Field
                type="textarea"
                :border="false"
                placeholder="请输入"
                :autosize="{ minHeight: 150 }"
                v-model="formData.couponCode"
              />
            </div>
          </div>
        </template>
      </Cell>
      <Cell class="sell-goods-cell" v-if="goodsInfo.cardType === 3">
        <template #title>
          <div>
            上传账号密码
            <span class="sell-goods-cell-cansell">
              当前可寄售数量{{ acquireNumber }}</span
            >
          </div>
        </template>
        <template #label>
          <div class="sell-goods-upload">
            <div class="sell-goods-upload-tips">
              每批次最大输入100个，卡券和卡密之间统一使用中英文逗号，以换行作为区分
            </div>
            <div class="sell-goods-upload-textarea">
              <Field
                type="textarea"
                :border="false"
                placeholder="请输入"
                :autosize="{ minHeight: 150 }"
                v-model="formData.couponCode"
              />
            </div>
          </div>
        </template>
      </Cell>
      <Cell class="sell-goods-cell" v-if="goodsInfo.cardType === 2">
        <template #title>
          <div class="batchUpload">
            <div class="batchUpload-left">
              <span class="batchUpload-title">上传照片</span>
              <span class="batchUpload-cansell">
                当前可寄售数量{{ acquireNumber }}</span
              >
            </div>
            <Uploader
              v-if="qrcodeList.length < 10"
              :after-read="afterRead"
              max-count="10"
              :max-size="1024 * 1024"
              @oversize="onOversize"
              multiple
            >
              <Button size="small" class="batchUpload-btn">批量上传</Button>
            </Uploader>
          </div>
        </template>
        <template #label>
          <div
            class="batchUpload-qrcodes"
            v-for="(qrcode, index) in qrcodeList"
            v-bind:key="index"
          >
            <div class="batchUpload-qrcodes-head">
              <div class="batchUpload-qrcodes-head-name">券{{ index + 1 }}</div>
              <div
                v-if="qrcodeList.length > 1"
                class="batchUpload-qrcodes-head-delete"
                @click="
                  () => {
                    qrcodeRemove(index)
                  }
                "
              >
                <van-icon name="delete" />
              </div>
            </div>
            <div class="batchUpload-qrcodes-item">
              <div class="batchUpload-qrcodes-item-name">上传二维码：</div>
              <div class="batchUpload-qrcodes-item-input">
                <Uploader
                  class="batchUpload-qrcodes-item-input-uploader"
                  :after-read="
                    (file) => {
                      afterRead(file, index)
                    }
                  "
                  max-count="10"
                  :max-size="1024 * 1024"
                  @oversize="onOversize"
                >
                  {{ qrcode.uploaded ? '已上传' : '点击上传' }}
                </Uploader>
              </div>
            </div>
            <div class="batchUpload-qrcodes-item">
              <div class="batchUpload-qrcodes-item-name">二维码信息：</div>
              <div class="batchUpload-qrcodes-item-input">
                <input
                  type="text"
                  placeholder="上传二维码自动填充，也可手动添加"
                  v-model="qrcode.info"
                  readonly
                />
              </div>
            </div>
            <div class="batchUpload-qrcodes-item">
              <div class="batchUpload-qrcodes-item-name">有效期：</div>
              <div
                class="batchUpload-qrcodes-item-input"
                @click="
                  () => {
                    showCalendar(index)
                  }
                "
              >
                <van-icon name="calendar-o" /><span
                  class="batchUpload-qrcodes-item-input-calendar-placeholder"
                  >{{ qrcode.pastTime || '填错日期无法回款' }}</span
                >
              </div>
            </div>
            <div
              class="batchUpload-qrcodes-add"
              v-if="index === qrcodeList.length - 1 && qrcodeList.length < 10"
            >
              <van-icon name="add" @click="qrcodeAdd" />
            </div>
          </div>
          <div class="batchUpload-lebel">
            上限10张，仅支持jpg或者png格式，且每张不超过1M
          </div>
        </template>
      </Cell>
      <Cell class="sell-goods-cell">
        <template #title>
          <div>注意事项</div>
        </template>
        <template #label>
          <div class="sell-goods-needknow">
            <div>
              1.严禁提交无效卡及错误卡、严禁上传拍照照片，否则将冻结账户!请上传带二维码和完整券号的整个屏幕截图。
            </div>
            <div>
              2.卡券最短有效期必须大于
              <span>最短有效期，有效期错误可能导致无法回款</span>
            </div>
            <div>
              3.平台仅限转让合法来源卡券，严禁利用本平台进行洗钱、欺诈、销赃等非法活动
            </div>
          </div>
        </template>
      </Cell>
    </CellGroup>
    <div class="common-space" style="height: 20px"></div>
    <div class="sell-goods-bottom">
      <div class="sell-goods-bottom-button">
        <div class="sell-goods-btn sell-goods-btn-backhome" @click="backhome">
          返回首页
        </div>
        <div
          class="goods-info-btn sell-goods-btn"
          :class="{
            'sell-btn-disabled': !saveStockAvailable.s,
          }"
          @click="saveStock"
        >
          寄售卡券
        </div>
        <!-- <Button
          :disabled="!saveStockAvailable.s"
          class="goods-info-btn"
          block
          round
          size="small"
          color="linear-gradient(138deg, #40424E 0%, #1E1F26 100%)"
          @click="saveStock"
          >寄售卡券</Button
        > -->
      </div>
    </div>
    <!-- <Popup v-model="goodsTypeShow" position="bottom" allow-html>
      <Picker
        show-toolbar
        :columns="goodsTypeColumns"
        @cancel="goodsTypeShow = false"
        @confirm="onGoodsTypeConfirm"
      />
    </Popup>
    <Popup v-model="cardTypeShow" position="bottom" allow-html>
      <Picker
        show-toolbar
        :columns="cardTypeColumns"
        @cancel="cardTypeShow = false"
        @confirm="onCardTypeConfirm"
      />
    </Popup>
    <Popup v-model="standardShow" position="bottom" allow-html>
      <Picker
        show-toolbar
        :columns="standardColumns"
        @cancel="standardShow = false"
        @confirm="onStandardConfirm"
      />
    </Popup> -->
    <Calendar
      :default-date="canlendarDate"
      v-model="calendarShow"
      @confirm="onCalendarConfirm"
      :min-date="minDate"
      ref="cal"
    />
    <van-overlay :show="confirmShow">
      <div class="model-wrapper" @click.stop>
        <div class="model-box">
          <div class="title">温馨提示</div>
          <div class="tips-content">
            请认真阅读商品出售规则，确保券码有效性，且保证7天有效期
          </div>
          <div class="checkboxs">
            <div>
              <van-checkbox
                v-model="confirmChecked"
                checked-color="#F86535"
                shape="square"
                icon-size="12px"
              >
                我确认上传正确货物：
              </van-checkbox>
              <span @click="agreementClick">{{ goodsInfo.skuName }}</span>
            </div>
            <div>
              <van-checkbox
                v-model="agreementChecked"
                shape="square"
                checked-color="#F86535"
                icon-size="12px"
              >
                我已阅读
              </van-checkbox>
              <span @click="agreementClick">《出卡拉卡券转让协议》</span>
            </div>
          </div>
          <div class="btns">
            <div class="closeBtn" @click="closeConfirm">取消</div>
            <div class="submitBtn" @click="submitConfirm">提交</div>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import {
  Cell,
  CellGroup,
  Field,
  Uploader,
  Button,
  Calendar,
  Notify,
} from 'vant'
import moment from 'moment'
import { upload_pic_post, checkImg_get } from '@/api/app/file_upload'
import { saveStock_post } from '@/api/front/goods'
import { detail_get } from '@/api/app/goods'
import util from '@/util/util'

let queryData
export default {
  name: 'index',
  components: {
    Cell,
    CellGroup,
    Field,
    Uploader,
    Button,
    Calendar,
  },
  data () {
    return {
      acquireNumber: 0,
      goodsTypeColumns: [],
      goodsTypeShow: false,
      cardTypeColumns: ['视频音乐', '餐饮美食', '饮品甜点', '电影阅读'],
      cardTypeShow: false,
      standardColumns: ['视频音乐', '餐饮美食', '饮品甜点', '电影阅读'],
      standardShow: false,
      calendarShow: false,
      agreementChecked: false,
      confirmChecked: false,
      fileList: [],
      formData: {
        pastTime: '',
        couponCode: '',
      },
      goodsInfo: {},
      qrcodeList: [
        {
          uploaded: false,
          info: '',
          pastTime: '',
          imgPath: '',
          success: false
        },
      ],
      openCanlendarIndex: 0,
      confirmShow: false,
    }
  },
  computed: {
    canlendarDate () {
      const v =
        this.goodsInfo.cardType === 2
          ? moment(this.qrcodeList[this.openCanlendarIndex].pastTime).toDate()
          : moment(this.formData.pastTime).toDate()
      return util.isValidDate(v) ? v : null
    },
    sellAgreementLink () {
      // 协议
      const agreementViewer =
        'https://m.shwzfa.cn/static/pdfjs/web/viewer.html?file='
      const agreementRoot = 'https://m.shwzfa.cn/static/agreement/'
      return `${agreementViewer}${encodeURIComponent(
        agreementRoot + 'goodssell.pdf'
      )}`
    },
    minDate () {
      return new Date(
        new Date().getTime() +
        (this.goodsInfo.minPeriod || 10) * 24 * 60 * 60 * 1000
      )
    },
    saveStockAvailable () {
      if (this.goodsInfo.cardType !== 2 && !this.formData.pastTime) {
        return {
          s: false,
          m: '请选择最短有效期',
        }
      }
      if (!this.cardInfoList || this.cardInfoList.length < 1) {
        return {
          s: false,
          m:
            this.goodsInfo.cardType === 2
              ? '请上传二维码！'
              : '请先添加卡密或者兑换码!',
        }
      }
      return {
        s: true,
      }
    },
    confirmAvailable () {
      if (!this.agreementChecked) {
        return {
          s: false,
          m: '请先同意用户协议哦！',
        }
      }
      if (!this.confirmChecked) {
        return {
          s: false,
          m: '请先确认上传正确货物！',
        }
      }
      return {
        s: true,
      }
    },
    cardInfoList () {
      if (
        (this.goodsInfo.cardType === 1 || this.goodsInfo.cardType === 3) &&
        !this.formData.couponCode
      ) {
        return null
      }
      if (this.goodsInfo.cardType === 1) {
        return this.formData.couponCode.split(/\n/).map((item) => {
          return {
            cardValue: item,
            pastTime: this.formData.pastTime,
          }
        })
      }
      if (this.goodsInfo.cardType === 3) {
        return this.formData.couponCode.split(/\n/).map((item) => {
          const arr = item.split(/[,|，]/)
          return {
            cardValue: arr[0],
            cardPwd: arr[1],
            pastTime: this.formData.pastTime,
          }
        })
      }
      if (this.goodsInfo.cardType === 2) {
        console.log(this.qrcodeList)
        return this.qrcodeList
          .filter((item) => {
            return !!item.success && item.pastTime
          })
          .map((item) => {
            return {
              cardValue: item.imgPath,
              pastTime: item.pastTime,
            }
          })
      }
      return null
    },
  },
  mounted () {
    queryData = this.$route.query
    this.acquireNumber = queryData.acquireNumber
    detail_get({
      data: {
        skuId: queryData.id,
      },
    }).then((res) => {
      this.goodsInfo = res
    })
  },
  methods: {
    backhome () {
      this.$router.push('/')
    },
    agreementClick () {
      location.href = this.sellAgreementLink
    },
    saveStock () {
      if (!this.saveStockAvailable.s) {
        Notify({
          type: 'danger',
          message: this.saveStockAvailable.m,
          duration: 1500,
        })
        return
      }
      this.confirmShow = true
    },
    onGoodsTypeConfirm (v) {
      this.formData.goodsType = v
      this.goodsTypeShow = false
    },
    showGoodsType () {
      this.goodsTypeShow = true
    },
    onCardTypeConfirm (v) {
      this.formData.cardType = v
      this.cardTypeShow = false
    },
    showCardType () {
      this.cardTypeShow = true
    },
    onStandardConfirm (v) {
      this.formData.skuName = v
      this.standardShow = false
    },
    showStandard () {
      this.standardShow = true
    },
    onCalendarConfirm (v) {
      console.log(v)
      if (this.goodsInfo.cardType === 2) {
        this.qrcodeList[this.openCanlendarIndex].pastTime = moment(v).format(
          'YYYY-MM-DD'
        )
      } else {
        this.formData.pastTime = moment(v).format('YYYY-MM-DD')
      }
      this.calendarShow = false
      this.openCanlendarIndex = 0
    },
    showCalendar (index) {
      this.calendarShow = true
      if (
        this.goodsInfo.cardType === 2 &&
        typeof index === 'number' &&
        !isNaN(index)
      ) {
        this.openCanlendarIndex = index
      }
    },
    onOversize () {
      this.$toast('文件大小不能超过 1MB')
    },
    async afterRead (file, index) {
      if (typeof index === 'object' && !Array.isArray(file)) {
        file = [file]
      }

      if (Array.isArray(file)) {
        if (10 - this.qrcodeList.length < file.length) {
          this.$toast('最多提交10张')
          return
        }
        this.$toast.loading({
          message: '上传中',
          forbidClick: true,
          duration: 0,
        })
        for (let i = 0; i < file.length; i++) {
          this.qrcodeList.push({
            uploaded: false,
            info: '',
            pastTime: '',
            imgPath: ''
          })
          const lastIndex = this.qrcodeList.length - 1
          const element = file[i]

          try {
            await this.upload(element, lastIndex)
          } catch (error) {
            this.$toast.clear()
          }
        }
        this.$toast.clear()
        return
      }

      this.$toast.loading({
        message: '上传中',
        forbidClick: true,
        duration: 0,
      })
      try {
        await this.upload(file, index)
      } catch (error) {
        this.$toast.clear()
      }
      this.$toast.clear()
    },
    async upload (file, index) {
      const param = new FormData() // 创建form对象
      param.append('file', file.file)

      const uploadRes = await upload_pic_post({
        data: param,
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      this.qrcodeList[index].uploaded = true
      this.qrcodeList[index].imgPath = uploadRes[0]
      await this.checkImg(uploadRes[0], index)
    },
    async checkImg (imgUrl, index) {
      console.log(imgUrl, index)
      try {
        const imgInfo = await checkImg_get({
          data: {
            imgUrl: imgUrl,
          },
        })
        this.qrcodeList[index].info = imgInfo
        this.qrcodeList[index].success = true
      } catch (error) {
        this.qrcodeList[index].info = error.message
        this.qrcodeList[index].success = false
      }
    },
    beforeDelete (res, info) {
      this.fileList.splice(info.index, 1)
      return true
    },
    qrcodeAdd () {
      this.qrcodeList.push({
        uploaded: false,
        info: '',
        pastTime: '',
      })
    },
    qrcodeRemove (index) {
      this.qrcodeList.splice(index, 1)
    },
    closeConfirm () {
      this.confirmShow = false
    },
    submitConfirm () {
      if (!this.confirmAvailable.s) {
        Notify({
          type: 'danger',
          message: this.confirmAvailable.m,
          duration: 1500,
        })
        return
      }
      saveStock_post({
        data: {
          cardInfoList: this.cardInfoList,
          skuId: this.goodsInfo.id,
        },
      }).then((res) => {
        Notify({
          type: 'success',
          message: '提交成功，等待出售',
          duration: 1500,
          onClose: () => {
            this.$router.push('/orderCenter')
          },
        })
      })
    },
  },
}
</script>
<style lang="scss" scoped src="./styles/index.scss"></style>
